package com.cz.nongyetongv5.adapter;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.utils.ImageUtil;

/**
 * 启动欢迎页面的Adapter
 */
public class WelcomePageAdapter extends PagerAdapter {

	private int[] imageIds = null;

	private OnClickListener onClickListener;

	public WelcomePageAdapter(int[] imageIds, OnClickListener onClickListener) {

		this.imageIds = imageIds;

		this.onClickListener = onClickListener;

	}

	/**
	 * 官方提示这么写
	 */
	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		// 官方提示这么写
		return arg0 == arg1;
	}

	/**
	 * 返回页卡的数量
	 */
	@Override
	public int getCount() {
		return this.imageIds != null ? this.imageIds.length : 0;
	}

	/**
	 * 销毁一个页卡
	 */
	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {

		ViewGroup group = (ViewGroup) object;

		ImageView ivGuide = (ImageView) group.findViewById(R.id.ivGuide);

		Bitmap image = ((BitmapDrawable) ivGuide.getDrawable()).getBitmap();

		image.recycle();

		image = null;

		container.removeView(group);
	}

	/**
	 * 获得元素的下标
	 */
	@Override
	public int getItemPosition(Object object) {
		return POSITION_NONE;
	}

	/**
	 * 获得Page标题
	 */
	@Override
	public CharSequence getPageTitle(int position) {
		return super.getPageTitle(position);
	}

	/**
	 * 实例化页卡
	 */
	@Override
	public Object instantiateItem(ViewGroup container, int position) {

		LayoutInflater layoutInflater = LayoutInflater.from(container
				.getContext());

		ViewGroup guideItem = (ViewGroup) layoutInflater.inflate(
				R.layout.guide_item, container, false);

		ImageButton btnInto = (ImageButton) guideItem
				.findViewById(R.id.btnInto);

		if (position == imageIds.length - 1) {

			btnInto.setVisibility(View.VISIBLE);

			btnInto.setOnClickListener(onClickListener);

		} else {

			btnInto.setVisibility(View.GONE);

		}

		ImageView ivGuide = (ImageView) guideItem.findViewById(R.id.ivGuide);

		// BitmapFactory.Options options = new BitmapFactory.Options();
		//
		// options.inSampleSize = 3;

		// ImageUtil.decodeSampledBitmapFromResource(res, reqWidth, reqHeight)

		Bitmap image = ImageUtil.decodeSampledBitmapFromResource(container
				.getContext().getResources(), imageIds[position], 360, 600);

		ivGuide.setImageBitmap(image);

		//
		ivGuide.setScaleType(ScaleType.CENTER_CROP);

		container.addView(guideItem);

		return guideItem;
	}


}
